package com.atzxh.datastructure.Stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author 小红同学
 * @create 2022-10-10-21:05
 * @description 基于后缀表达式的简单计算器
 */
public class PolandNotation {
    public static void main(String[] args) {

        //(30+4)*5-6 -->  34+5*6-      中缀转后缀
        String expression = "1+(3*5)-6";



    }

    public static List<String> getArrayList(String suffixExpression) {
        String[] spit = suffixExpression.split(" ");
        List<String> list = new ArrayList<>();

        for (String ele : spit) {
            list.add(ele);
        }
        return list;
    }

    public static int calculate(List<String> list) {
        //创建一个栈
        Stack<String> stack = new Stack<>();
        //遍历传进来的list
        for (String item : list) {
            //用正则表达式来匹配是不是多位数
            if (item.matches("\\d+")) {
                stack.push(item);
            } else {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int result = 0;
                switch (item) {
                    case "+":
                        result = num1 + num2;
                        break;
                    case "-":
                        result = num1 - num2;
                        break;
                    case "*":
                        result = num1 * num2;
                        break;
                    case "/":
                        result = num1 / num2;
                        break;
                    default:
                        throw new RuntimeException("运算符有误");
                }
                //把运算结果入栈
                stack.push("" + result);
            }
        }
        //遍历最后留在栈中的元素就是最后结果
        return Integer.parseInt(stack.pop());
    }
}
